from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
import random
import string
from captcha.image import ImageCaptcha
import redis
from django.http import HttpResponse
# Create your views here.
from myapp.models import Users


# 校验用户名
class CheckUserName(APIView):
    def get(self, request, name):
        rest = Users.objects.filter(username=name).count()
        if rest > 0:
            return Response(
                {'msg': '用户名已经存在', 'code': 400}
            )
        return Response({'code': 200})


# 校验手机号
class CheckMobile(APIView):
    def get(self, request, mobile):
        rest = Users.objects.filter(mobile=mobile).count()
        if rest > 0:
            return Response(
                {'msg': '手机号已经存在', 'code': 400}
            )
        return Response({'code': 200})


# 生成图片验证码
class TuCode(APIView):
    def get(self, request, uuid):
        salt = ''.join(random.sample(string.ascii_letters + string.digits, 4))
        img = ImageCaptcha()
        image = img.generate(salt)
        redis_cli = redis.Redis(host='127.0.0.1', port=6379)
        imgid = "img_{}".format(uuid)
        redis_cli.setex(imgid, 120, salt)
        return HttpResponse(image, content_type="image/png")


# 校验图片验证码
class CheckTu(APIView):
    def get(self, request):
        image_id = request.query_params.get('imageCodeID')
        image_code = request.query_params.get('imageCode')
        redis_cli = redis.Redis(host='127.0.0.1', port=6379)
        res = redis_cli.get("img_{}".format(image_id))
        if res:
            if res.decode().lower() == image_code.lower():
                return Response({'code': 200})
            else:
                return Response({'msg': '验证码输入有误！'})
        else:
            return Response({'msg': '验证码已经过期'})


# 注册
class Register(APIView):
    def post(self, request):
        name = request.data.get('userName')
        pwd = request.data.get('pwd')
        mobile = request.data.get('mobile')
        agree = request.data.get('agree')
        if not all([name, pwd, mobile]):
            return Response(
                {'msg': '请输入完整的信息', 'code': 400}
            )
        if not agree:
            return Response(
                {'msg': '请勾选同意协议', 'code': 400}
            )
        Users.objects.create_user(username=name, password=pwd, mobile=mobile)
        return Response({'msg': '注册成功', 'code': 200})
